<?php

namespace App\Domain\Role\Dao;


use App\Domain\Account\Models\AccountHasRoles;
use App\Domain\Account\Models\AccountModel;
use App\Domain\Permissions\Models\PermissionsModel;
use App\Domain\Role\Models\RoleModel;
use App\Exceptions\BadRequestException;
use Illuminate\Database\Eloquent\Builder;


class RoleDao
{
    public static function findById($id)
    {
        return RoleModel::query()->where(['id' => $id])->first();
    }

    public static function findByName($name)
    {
        return RoleModel::query()->where(['name' => $name])->first();
    }

    public static function findAll()
    {
        return RoleModel::query()->get();
    }

    /**
     * 创建角色
     * @param $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|RoleModel
     */
    public function create($params)
    {
        return RoleModel::create($params);
    }

    /**
     * 修改角色
     * @param RoleModel $role
     * @param $params
     * @return RoleModel
     */
    public function update(RoleModel $role, $params)
    {
        $role->fill($params)->save();
        return $role;
    }

    /**
     * 删除角色和角色权限
     * @param $roleId
     */
    public function delete($roleId)
    {
        $role = RoleModel::findById($roleId);
        //检测有没有被分配给用户
        $count = AccountHasRoles::where('role_id', $roleId)->count();
        if ($count > 0) {
            $accounts = AccountModel::join('model_has_roles', function ($join) use ($roleId) {
                return $join->where('role_id', $roleId);
            })->get();
            $accountMsg = [];
            foreach ($accounts as $account) {
                $accountMsg[] = ($account['organization_name'] . '-' . $account['name']);
            }
            throw new BadRequestException('角色正在使用中，请先停止使用。' . join(';', $accountMsg));
        }
        $role->delete();
    }

    /**
     * 获取角色的所有权限ID
     * @param $roleIdList
     * @return PermissionsModel[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Builder[]|Collection
     */
    public function getPermissionModelByRoleIds($roleIdList)
    {
        return PermissionsModel::query()
            ->select('permissions.*')
            ->leftJoin('role_has_permissions', 'role_has_permissions.permission_id', '=', 'permissions.id')
            ->where('role_has_permissions.role_id', $roleIdList)
            ->groupBy('permissions.id')
            ->get();
    }
}
